package com.zgroup.controllers.admin

import com.zgroup.domain.SysUser
import javax.servlet.http.Cookie
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import org.apache.commons.codec.digest.DigestUtils
import com.zgroup.common.*

class SysUserController extends AdminDispatchController {

  def mailService
  def jcaptchaService

  def sysUserService

  def beforeInterceptor = [
          action: this.&auth,
          except: ['login']
  ]

  def auth() {
    request["pageIndex"] = 3
    return super.auth()
  }

  String randomPass() {
    UUID uuid = UUID.randomUUID()
    uuid.toString()[0..7]
  }

  /**
   * 删除身份信息
   * @param response
   * @param user
   */
  static void delIdentity(HttpServletResponse response) {
    Cookie userNameCookie = new Cookie(SysUser.COOKIE_USER_NAME, null);
    Cookie passwordCookie = new Cookie(SysUser.COOKIE_PASSWORD, null);

    // 设定临时Cookie
    userNameCookie.setMaxAge(0);
    passwordCookie.setMaxAge(0);
    userNameCookie.setPath("/");
    passwordCookie.setPath("/");

    response.addCookie(userNameCookie);
    response.addCookie(passwordCookie);
  }
  /**
   * 保存身份信息
   * @param response
   * @param user
   * @throws Exception
   */
  static void saveIdentity(HttpServletResponse response, SysUser user, boolean remember_password) {
    String encryptUserName = CipherUtils.encrypt(user.username);
    Cookie userNameCookie = new Cookie(SysUser.COOKIE_USER_NAME,
            encryptUserName);
    Cookie passwordCookie = new Cookie(SysUser.COOKIE_PASSWORD,
            CipherUtils.encrypt(user.password));
    int maxAge = -1;
    // 设定临时Cookie
    if (remember_password) {
      maxAge = Constants.COOKIE_MAX_AGE;
    }
    // 设定临时Cookie
    userNameCookie.setMaxAge(maxAge);
    passwordCookie.setMaxAge(maxAge);
    userNameCookie.setPath("/");
    passwordCookie.setPath("/");

    response.addCookie(userNameCookie);
    response.addCookie(passwordCookie);
  }

  /**
   * 通过cookie得到用户情报
   * @param request
   * @return
   * @throws Exception
   */
  public static SysUser getUserInfo(HttpServletRequest request) {
    String username = null;
    String password = null;
    String[] keys = new String[2];
    keys[0] = SysUser.COOKIE_USER_NAME;
    keys[1] = SysUser.COOKIE_PASSWORD;
    Map info = WebUtils.getInfoByCookie(request, keys);

    if (info.isEmpty()) {
      return null;
    }

    try {
      username = CipherUtils.decrypt((String) info.get(SysUser.COOKIE_USER_NAME));
      password = CipherUtils.decrypt((String) info.get(SysUser.COOKIE_PASSWORD));
    } catch (Exception e) {
      return null;
    }

    return SysUser.findByUsernameAndPassword(username, password)
  }

  /**
   * 忘记密码
   */
  def passwordReminder = {
    if (request.method == 'POST') {
      def user = SysUser.findByUsername(params.username)
      if (user && user.username != 'admin') {
        def newPassword = randomPass()
        user.password = DigestUtils.shaHex(newPassword)
        user.save()
        //                mailService.sendMail {
        //                    from "wiki@grails.org"
        //                    to user.email
        //                    title "Grails.org password reset"
        //                    body "Your password has been reset. Please login with the following password: ${newPassword}"
        //                }
      } else {
        flash.message = "Username not found"
      }
    }
  }

  /**
   * ajax验证邮箱，昵称唯一性验证
   */
  def validate = {
    def user = null;
    // 邮箱唯一性验证
    if (params.email != null) {
      user = SysUser.findByUsername(params.email)
      // 昵称唯一性验证
//        }else if(params.nickname!=null){
//            user = SysUser.findByNickname(params.nickname)
    } else {
      render "1"
      return
    }
    if (user) {
      render "0"
    } else {
      render "1"
    }
  }

  /**
   * 登录
   */
  def login = {
    if (request.method == 'POST') {
      if (!CheckUtils.isEmpty(params.captchaResponse)) {
        if (!jcaptchaService.validateResponse("imageCaptcha", session.id, params.captchaResponse)) {
          flash.message = "验证码填写不正确。"
          [bo: params]
          return
        }
      }

      def user = SysUser.findByUsernameAndPassword(params.p_username, CipherUtils.md5(params.p_password))
      if (user) {
        saveIdentity(response, user, params.remember_password == 'true')
        redirect(controller: "frame", action: "index")
        return
      } else {
        flash.message = "登录邮箱或密码不正确。"
        [bo: params]
      }
    }
  }

  /**
   * 退出
   */
  def logout = {
    delIdentity(response)
    forward(action: "forwardURL")
  }

  /**
   * 个人信息
   */
  def profile = {
    if (request.method == 'POST') {
      def user = request[SysUser.REQUEST_USER_INFO]

      bindData(user, params)
      if (params.name != null) {
        def headFile = request.getFile("headFile")
        // 头像上传
        if (headFile != null && !headFile.isEmpty()) {
          def webRootDir = grailsApplication.config.grails.imagesRealPath
          def userDir = new File(webRootDir, SysUser.UPLOAD_FILE_PATH)
          userDir.mkdirs()
          if (!CheckUtils.isEmpty(user.headPicture)) {
            def oldHeadImg = new File(userDir, user.headPicture)
            oldHeadImg.delete()
            user.headPicture = null
          }
          def fileName = WebUtils.generateUuidHex() + WebUtils.getFileExt(headFile.originalFilename)
          def headImg = new File(userDir, fileName)
          headFile.transferTo(headImg)
          user.headPicture = fileName
          String imgPath = webRootDir + SysUser.UPLOAD_FILE_PATH + user.headPicture
          ImageUtils.resize(imgPath, imgPath, 100, 96);
        }
      } else if (params.homeEstateId != null) {
        if (CheckUtils.isEmpty(params.homeEstatePrivacyFlag)) {
          user.homeEstatePrivacyFlag = "0"
        }
        user.homeEstate = Estate.get(params.homeEstateId)
      } else if (params.companyId != null) {
        if (CheckUtils.isEmpty(params.companyPrivacyFlag)) {
          user.companyPrivacyFlag = "0"
        }
        user.company = Company.get(params.companyId)
      } else if (params.companyEstateId != null) {
        if (CheckUtils.isEmpty(params.companyEstatePrivacyFlag)) {
          user.companyEstatePrivacyFlag = "0"
        }
        user.companyEstate = Estate.get(params.companyEstateId)
      }

      if (!user.save()) {
        user.errors.each {
          println it
        }
      }
    }
  }
}
